package com.lxs.doc.rocess.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class ExtractImageUtil {
    public static Map<String, String> extractImages(Sheet sheet) {
        Map<String, String> imageMap = new HashMap<>(); // 存储图片Base64编码
        Drawing drawing = sheet.getDrawingPatriarch();

        if (drawing instanceof XSSFDrawing) {
            for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes() ){
                if (shape instanceof XSSFPicture) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    // 获取图片数据
                    XSSFPictureData pictureData = picture.getPictureData();
                    // 处理图片...
                    String ext = getImageExtension(pictureData);
                    byte[] data = pictureData.getData();
                    String base64 = Base64.getEncoder().encodeToString(data);
                    imageMap.put(getAnchorKey(pictureData,picture),
                            "<img src='data:image/" + ext + ";base64," + base64 + "'/>");
                }
            }
        }
        return imageMap;
    }

    // 图片格式识别
    private static String getImageExtension(PictureData pictureData) {
        int type = pictureData.getPictureType();
        switch (type) {
            case Workbook.PICTURE_TYPE_JPEG: return "jpeg";
            case Workbook.PICTURE_TYPE_PNG:  return "png";
            case XSSFWorkbook.PICTURE_TYPE_GIF:  return "gif";
            default: return "octet-stream"; // 通用二进制格式
        }
    }
    // 生成图片锚点唯一标识
    private static String getAnchorKey(PictureData pictureData, XSSFPicture picture) {
        XSSFClientAnchor anchor = (XSSFClientAnchor) picture.getAnchor();
        return anchor.getRow1() + "-" + anchor.getCol1();
    }
    // 获取单元格图片锚点
    public static String getCellImageKey(Cell cell) {
        return cell.getRowIndex() + "-" + cell.getColumnIndex();
    }
    // 特殊处理EMF/WMF格式
//    private byte[] convertVectorImage(byte[] data) {
//        // 使用Java ImageIO进行格式转换
//        try {
//            BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            ImageIO.write(img, "png", baos);
//            return baos.toByteArray();
//        } catch (Exception e) {
//            return data; // 转换失败返回原数据
//        }
//    }
}
